package com.winz.cultureapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.mine.xrecyclerview.ExpandListView;
import com.winz.cultureapp.R;
import com.winz.cultureapp.adapter.BookStadiumAdapter;
import com.winz.cultureapp.application.DemoApplication;
import com.winz.cultureapp.base.BaseAppCompatActivity;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.BookFixBean;
import com.winz.cultureapp.entity.BookStadiumTimeBean;
import com.winz.cultureapp.entity.request.UnitBookFixReq;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.RequestFactory;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.utils.FormatUtils;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.winz.cultureapp.utils.SharePrefsUtil;
import com.winz.cultureapp.widge.TimerSelector;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 预定场馆
 */
public class BookStadiumActivity extends BaseAppCompatActivity implements TimerSelector.OkClickListener {
    @BindView(R.id.tv_top_title)
    TextView mTv_top_title;
    @BindView(R.id.tv_date)
    TextView mTv_date;
    @BindView(R.id.tv_time)
    TextView mTv_time;
    @BindView(R.id.elv_data)
    ExpandListView mElv_data;
    @BindView(R.id.et_name)
    EditText mEt_name;
    @BindView(R.id.et_phone)
    EditText mEt_phone;

    private String id;
    private String title;

    private double fee;


    private TimerSelector ts_date;
    private String date = FormatUtils.millis2Str(System.currentTimeMillis(),"yyyy-MM-dd");
    private long time;

    private BookStadiumAdapter mAdapter;
    private List<BookStadiumTimeBean.DataBean.ListBean> mDatas;

    @Override
    protected int contentView() {
        return R.layout.activity_book_stadium;
    }

    @Override
    protected void initViews() {
        setStatusBar(getResources().getColor(R.color.base_color));
        mDatas = new ArrayList<>();
        mTv_time.setText(date);
        mTv_date.setText(date);
        ts_date = new TimerSelector(this, "yyyy-MM-dd");
        ts_date.setOkClickListener(this);
        mAdapter = new BookStadiumAdapter(this, true, R.layout.item_book_stadium_time);
        mElv_data.setAdapter(mAdapter);
    }

    @Override
    protected void initEvents() {
        mElv_data.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mDatas.get(i).scheduleStatus == 1) {
                    mAdapter.cleanAllState();
                    mAdapter.changeSel(i);
                    mAdapter.setLastSeletPosition(i);
                }
            }
        });
    }

    @Override
    protected void loadDatas(Intent intent) {
        if (intent != null) {
            if (intent.getExtras() != null) {
                id = intent.getExtras().getString(Constants.KEY.STADIUM.ITEM_ID);
                title = intent.getExtras().getString(Constants.KEY.STADIUM.ITEM_TITLE);
                fee = intent.getExtras().getDouble(Constants.KEY.STADIUM.ITEM_FEE);
                mTv_top_title.setText(title == null ? "茂名羽毛球馆1" : title);
                if (TextUtils.isEmpty(id)){
                    showMsg("场馆ID不存在");
                }else {
                    getList();
                }
            }
        }
    }

    private void getList() {
        showProgressDialog();
        HttpUitls.onGet("unit_book_schedule", RequestFactory.getInstance().unit_book_schedule(date,id),new OnResponeListener<BookStadiumTimeBean>() {
            @Override
            public void onSuccess(BookStadiumTimeBean bean) {
                Logger.d("unit_book_schedule==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0){
                    mDatas.clear();
                    mDatas = bean.data.list;
                    for (BookStadiumTimeBean.DataBean.ListBean entity:mDatas){
                        long endTime = FormatUtils.str2Millis(entity.scheduleDay + " " + entity.endTime, "yyyy-MM-dd HH:mm");
                        if (System.currentTimeMillis() - endTime>0 && entity.scheduleStatus == 1){
                            entity.scheduleStatus = 0;
                        }
                    }
                    mAdapter.setDatas(mDatas);
                }else {
                    showMsg(bean.msg);
                }

                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                Logger.d("unit_book_schedule==>>", error);
            }
        });
    }

    @OnClick({R.id.fl_back, R.id.ll_time,R.id.tv_ok})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_back:
                finish();
                break;
            case R.id.ll_time:
                ts_date.show(mTv_time, 0);
                break;
            case R.id.tv_ok: // 预定

                // 判断是否已登录
                if (DemoApplication.getInstance().isLogin){
                    if (isAllRight()){
                        commit();
                    }
                }else {
                    startActivity(LoginActivity.class,false);
                }
                break;
        }
    }

    private boolean isAllRight() {

        if (TextUtils.isEmpty(mEt_name.getText())){
            showMsg("请输入预定者姓名");
            return false;
        }
        if (TextUtils.isEmpty(mEt_phone.getText())){
            showMsg("请输入手机号码");
            return false;
        }
        if (mAdapter.getLastSeletPosition() == -1){
            showMsg("请选择预定时间段");
            return false;
        }
        return true;
    }

    /**
     * 提交预定
     */
    private void commit() {
        showProgressDialog();
        String token = SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN);
        HttpUitls.onPostByToken("unit_book_fix",token,
                new UnitBookFixReq(getEditTextStr(mEt_phone),
                        getEditTextStr(mEt_name),
                        mDatas.get(mAdapter.getLastSeletPosition()).unitScheduleRecordId,
                        id),
                new OnResponeListener<BookFixBean>() {
            @Override
            public void onSuccess(BookFixBean bean) {
                HttpUitls.isExpire(bean.code);
                Logger.d("unit_book_fix==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0){
                    if (fee == 0){
                        // 不需要支付
                        showMsg("预定成功");
                        setResult(RESULT_OK);
                        Bundle bundle = new Bundle();
                        bundle.putInt("index",0);
                        startActivity(PersonalRecordActivity.class, true,bundle);

                    }else {
                        // 调支付
                        startActivity(BookStadiumConfirmActivity.class,false);
                    }

                }else {
                    showMsg(bean.msg);
                }

                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                Logger.d("unit_book_fix==>>", error);
            }
        });

    }

    /**
     * 时间选择器
     *
     * @param view
     * @param date
     * @param time
     * @param flag
     */
    @Override
    public void okClick(View view, String date, long time, int flag) {
        if (flag == 0) {
            mTv_time.setText(date);
            mTv_date.setText(date);
            this.date = date;
            this.time = time;
            getList();
        }
    }

}
